from django.shortcuts import render
from base_utils.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin
from . import serializers
from base_utils.response import Response
from base_utils.response_http_code import BadRequestStatus
from apps.user.models import UserModel
from base_utils.paginator import ApiPagination
from django_q.tasks import async_task
from django_q.models import Schedule
from q_scheduler.async_tasks import tests_async
from q_scheduler.scheduler_tasks import api_create_task



# Create your views here.
# 登录
class LoginAPIView(APIView):
    authentication_classes = []

    def post(self, request, *args, **kwargs):
        ser = serializers.LoginSer(data=request.data)
        if ser.is_valid():
            data = ser.save()
            return Response(data=data)
        else:
            msg = self.get_errors_str(ser.errors)
            return Response(code=BadRequestStatus.http_code, msg=msg)


# 用户使用
class UserAPIView(APIView):

    # 测试分页器手动调用是否可用
    def get(self, request, *args, **kwargs):
        instance = UserModel.objects.filter(is_deleted=False)
        ser_class = serializers.UserSer
        page = ApiPagination()
        page_data = page(instance, request, ser_class)
        return Response(data=page_data, jk="luoli")

    def post(self, request, *args, **kwargs):
        ser = serializers.UserSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(data=ser.validated_data)
        else:
            msg = self.get_errors_str(ser.errors)
            return Response(code=BadRequestStatus.http_code, msg=msg)


# 测试分页器是否可用
class UsersAPIView(GenericViewSet, ListModelMixin):
    authentication_classes = []
    queryset = UserModel.objects.all()
    serializer_class = serializers.UserSer


# 测试异步任务执行
class AsyncTaskAPIView(APIView):
    authentication_classes = []
    def get(self, request, *args, **kwargs):
        async_task('q_scheduler.async_tasks.tests_async')
        return Response()

# 实时创建定时任务
class SchedulerTaskAPIView(APIView):
    authentication_classes = []
    def get(self,request,*args,**kwargs):
        schedule1 = Schedule.objects.create(
            func='q_scheduler.scheduler_tasks.api_create_task',
            schedule_type=Schedule.ONCE,
            minutes=1  # 5分钟后执行
        )
        return Response(data={'task_id':schedule1.id})
